/* eslint-disable prefer-promise-reject-errors */
const Const = require('./const')
const Data = require('./data')
const Util = require('./util')

let apiList = {
  Wx: {
    decrypt: ['~POST|wx/decrypt', 'code', 'app']
  },
  User: {
    loginByWx: ['~POST|user/login-by-wx', 'outer_user_id', 'union_id', 'outer_data', 'app'],
    getUserInfo: ['GET|user/info'],
    updateUserInfo: ['POST|user/info-update', 'avatar', 'nickname', 'birthday', 'gender', 'province', 'city', 'county', 'address'],
    usersInfo: ['GET|user/info-by-uid', 'uids'],
    updateNickname: ['POST|user/nickname-update', 'nickname'],
    userTrackByScan: ['POST|user/user-track-by-scan', 'json'],
    userTrackInfo: ['GET|user/user-track-info']
  },
  Post: {
    indexList: ['~GET|post/index-list', 'limit'],
    postList: ['~GET|post/list', 'label_id', 'page', 'category'],
    postListByCategory: ['~GET|post/list-by-category', 'category', 'page', 'limit'],
    postDetail: ['~GET|post/detail', 'post_id'],
    postDetailByAlias: ['GET|post/detail-by-alias', 'alias']
  },
  TpCode: {
    tpCodeList: ['~GET|tp-code/list', 'name']
  },
  Index: {
    getHomePage: ['~GET|index/home-page', 'json'],
    search: ['~GET|index/search', 'keywords']
  },
  Hospital: {
    getSchedule: ['~GET|hospital/schedule', 'schedule_id'],
    getConsultList: ['~GET|hospital/consult-list', 'hospital_id']
  },
  HospitalCard: {
    getHospitalCardList: ['GET|hospital-card/list'],
    getHospitalCardDetail: ['GET|hospital-card/detail', 'hospital_card_id'],
    saveHospitalCard: ['POST|hospital-card/save', 'hospital_card_id', 'name', 'wx_account', 'birthday', 'gender', 'body_weight', 'body_height', 'contact',
      'visit_time', 'anaphylaxis', 'address', 'description', 'img_list'],
    deleteHospitalCard: ['POST|hospital-card/delete', 'hospital_card_id'],
    getRecordList: ['GET|hospital-card/record-list'],
    getRecordDetail: ['GET|hospital-card/record-detail', 'id'],
    saveRecord: ['POST|hospital-card/record-save', 'type', 'img', 'content'],
    delRecord: ['POST|hospital-card/record-delete', 'id']
  },
  Order: {
    orderList: ['GET|order/list', 'page', 'status'],
    orderDetail: ['GET|order/detail', 'order_id'],
    orderDetailBySn: ['GET|order/detail-by-sn', 'order_sn'],
    orderSign: ['GET|order/order-sign', 'order_id'],
    createOrder: ['POST|order/order-create', 'type', 'goods_spec_id', 'amount', 'id_string', 'address_id', 'comment'],
    deleteOrder: ['POST|order/order-delete', 'order_id'],
    remindOrder: ['GET|order/delivery-remind', 'order_id'],
    updateOrderAddress: ['POST|order/order-update-address', 'order_id', 'address_id'],
    createVipOrder: ['POST|order/vip-order-create', 'vip_level']
  },
  Cart: {
    deleteCart: ['POST|goods-cart/delete', 'goods_cart_id_list'],
    addCart: ['POST|goods-cart/goods-cart-add', 'goods_id', 'goods_spec_id', 'amount'],
    updateCart: ['POST|goods-cart/goods-cart-update', 'goods_cart_id', 'amount'],
    cartList: ['GET|goods-cart/list'],
    cartListByIds: ['GET|goods-cart/list-by-ids', 'ids']
  },
  Goods: {
    bannerList: ['~GET|goods/banner-list', 'hospital_id'],
    goodsList: ['~GET|goods/list', 'name', 'page', 'category'],
    goodsDetail: ['~GET|goods/detail', 'goods_id'],
    goodsEvaluationList: ['~GET|goods/goods-evaluation-list', 'goods_id', 'page'],
    saveGoodsEvaluation: ['POST|goods/goods-evaluation-save', 'order_id', 'goods_id', 'level', 'content'],
    batchSaveGoodsEvaluation: ['POST|goods/goods-evaluation-batch-save', 'order_id', 'data']
  },
  UserAddress: {
    addressList: ['GET|user-address/list'],
    deleteAddress: ['GET|user-address/delete', 'address_id'],
    addressDetail: ['GET|user-address/detail', 'address_id'],
    saveAddress: ['POST|user-address/save', 'address_id', 'name', 'phone', 'province', 'city', 'county', 'address', 'is_default']
  },
  Pay: {
    payOrder: ['POST|pay/order-pay', 'order_sn']
  },
  VIP: {
    vipInfo: ['GET|user-vip/info'],
    vipConfigList: ['GET|user-vip/vip-config-list']
  },
  Config: {
    detail: ['~GET|config/detail', 'hospital_id', 'target_location', 'target_type']
  }
}

let api = {}

for (let moduleKey in apiList) {
  let moduleApiList = apiList[moduleKey]
  api[moduleKey] = {}
  for (let functionName in moduleApiList) {
    let config = moduleApiList[functionName]
    api[moduleKey][functionName] = (function (config) {
      return function () {
        let reqAction = config[0].split('|')
        let method = reqAction[0]
        let action = reqAction[1]
        let data = {}
        if (config.length > 1) {
          for (let i = 1; i < config.length; i++) {
            let key = config[i]
            let value = arguments[i - 1]
            if (value === undefined) {
              continue
            }
            data[key] = value
          }
        }
        return request(method, action, data)
      }
    })(config)
  }
}

function transformObjectToUrlencodedData (obj) {
  let p = []
  for (let key in obj) {
    if (obj.hasOwnProperty(key)) {
      p.push(encodeURIComponent(key) + '=' + encodeURIComponent(obj[key]))
    }
  }

  return p.join('&')
}

function request (method, url, params) {
  let token = Data.getToken() || ''
  let host = Const.NET.END_POINT
  return new Promise((resolve, reject) => {
    let requestData = ''

    if (Util.startWith(method, '~')) {
      requestData = Object.assign({}, params)
    } else {
      if (!token) {
        wx.showModal({
          title: '',
          content: '请先登录',
          showCancel: false,
          success: function () {
            wx.navigateTo({
              url: '/pages/登录页/main'
            })
          }
        })
        return false
      } else {
        requestData = Object.assign({
          token: token
        }, params)
      }
    }

    method = method.replace('~', '')

    console.info(`${host}/${url}?${transformObjectToUrlencodedData(requestData)}`)

    wx.request({
      url: `${host}/${url}`,
      data: requestData,
      method: method,
      header: { 'content-type': 'application/x-www-form-urlencoded' },
      success: function (res) {
        if (res.data.hasOwnProperty('code') && res.data.code === 2) {
          // wx.showToast({
          //   title: res.data.message,
          //   icon: 'success'
          // })
        }
        if (res.data.hasOwnProperty('code')) {
          let code = res.data.code
          if ([0, 2].indexOf(code) > -1) {
            if (code === 0) {
              resolve(res.data.data)
            } else {
              /**
               * 当客户端开发环境切换访问域名时
               * 会出现token验证失败的情况
               * 清空本地缓存方便操作
               */
              Data.set('token', '')
              Data.set('wx-user', '')
              Data.set('user', '')
              reject({
                code: res.data.code,
                message: '登录信息过期'
              })
              wx.navigateTo({
                url: '/pages/登录页/main'
              })
              // wx.reLaunch({
              //   url: url
              // });
            }
          } else {
            handlerError(res, reject)
          }
        } else {
          handlerError(res, reject)
        }
      },
      fail: function (reason) {
        reject({
          code: Const.ERROR.ERROR_NETWORK,
          response: reason
        })
      }
    })
  })
}

function handlerError (res, reject) {
  let message = res.data.message

  wx.showModal({
    title: '',
    content: (res.data && res.data.message) || '数据获取失败',
    showCancel: false,
    success: function () {
      // if (message === 'wrong space') {
      //   Util.reLaunchGo('/pages/未访问/main')
      // }

      reject({
        code: res.data.code,
        message: res.data.message
      })
    }
  })
}

module.exports = api
